/**
 * 工作台页面逻辑
 * 负责展示统计数据、最近活动、转换趋势等信息
 */

class DashboardManager {
    constructor() {
        this.refreshInterval = null;
        this.chart = null;
        this.init();
    }

    init() {
        this.checkAndSeedData();
        this.loadDashboardData();
        this.setupAutoRefresh();
        this.initChart();
    }

    /**
     * 检查并初始化模拟数据
     */
    async checkAndSeedData() {
        try {
            // 首先检查是否有数据
            const statsResponse = await axios.get('/api/dashboard/stats');
            
            // 如果没有数据，则生成模拟数据
            if (statsResponse.data.success && statsResponse.data.data.totalTasks === 0) {
                console.log('正在初始化模拟数据...');
                await axios.post('/api/dashboard/seed-data');
                console.log('模拟数据初始化完成');
            }
        } catch (error) {
            console.warn('初始化模拟数据失败:', error);
        }
    }

    /**
     * 加载工作台数据
     */
    async loadDashboardData() {
        try {
            // 并行加载所有数据
            const [statsResponse, activitiesResponse, trendResponse] = await Promise.all([
                this.loadStats(),
                this.loadRecentActivities(),
                this.loadConversionTrend()
            ]);

            // 更新统计卡片
            if (statsResponse.success) {
                this.updateStatsCards(statsResponse.data);
            }

            // 更新最近活动
            if (activitiesResponse.success) {
                this.updateRecentActivities(activitiesResponse.data);
            }

            // 更新图表
            if (trendResponse.success) {
                this.updateChart(trendResponse.data);
            }

        } catch (error) {
            console.error('加载工作台数据失败:', error);
            this.showError('加载工作台数据失败，请稍后重试');
        }
    }

    /**
     * 加载统计数据
     */
    async loadStats() {
        try {
            const response = await axios.get('/api/dashboard/stats');
            return response.data;
        } catch (error) {
            console.error('加载统计数据失败:', error);
            // 返回默认数据
            return {
                success: true,
                data: {
                    todayUploads: 0,
                    todayConversions: 0,
                    successRate: 0,
                    pendingErrors: 0
                }
            };
        }
    }

    /**
     * 加载最近活动
     */
    async loadRecentActivities() {
        try {
            const response = await axios.get('/api/dashboard/recent-activities');
            return response.data;
        } catch (error) {
            console.error('加载最近活动失败:', error);
            return {
                success: true,
                data: []
            };
        }
    }

    /**
     * 加载转换趋势数据
     */
    async loadConversionTrend() {
        try {
            const response = await axios.get('/api/dashboard/conversion-trend');
            return response.data;
        } catch (error) {
            console.error('加载转换趋势失败:', error);
            return {
                success: true,
                data: []
            };
        }
    }

    /**
     * 更新统计卡片
     */
    updateStatsCards(stats) {
        // 今日上传
        const todayUploadsElement = document.querySelector('.xiaomi-stat-card.orange .stat-number');
        if (todayUploadsElement) {
            this.animateNumber(todayUploadsElement, stats.todayUploads);
        }

        // 今日转换
        const todayConversionsElement = document.querySelector('.xiaomi-stat-card.blue .stat-number');
        if (todayConversionsElement) {
            this.animateNumber(todayConversionsElement, stats.todayConversions);
        }

        // 成功率
        const successRateElement = document.querySelector('.xiaomi-stat-card.green .stat-number');
        if (successRateElement) {
            this.animateNumber(successRateElement, stats.successRate, '%');
        }

        // 待处理错误
        const pendingErrorsElement = document.querySelector('.xiaomi-stat-card.red .stat-number');
        if (pendingErrorsElement) {
            this.animateNumber(pendingErrorsElement, stats.pendingErrors);
        }
    }

    /**
     * 数字动画效果
     */
    animateNumber(element, targetNumber, suffix = '') {
        const currentNumber = parseInt(element.textContent) || 0;
        const increment = (targetNumber - currentNumber) / 20;
        let current = currentNumber;

        const timer = setInterval(() => {
            current += increment;
            if ((increment > 0 && current >= targetNumber) || (increment < 0 && current <= targetNumber)) {
                current = targetNumber;
                clearInterval(timer);
            }
            
            if (suffix === '%') {
                element.textContent = current.toFixed(1) + suffix;
            } else {
                element.textContent = Math.round(current).toLocaleString() + suffix;
            }
        }, 50);
    }

    /**
     * 更新最近活动
     */
    updateRecentActivities(activities) {
        const activityList = document.querySelector('.activity-list');
        if (!activityList) return;

        if (activities.length === 0) {
            activityList.innerHTML = `
                <div class="text-center text-muted py-4">
                    <i class="fas fa-inbox fa-2x mb-3 d-block"></i>
                    <p>暂无最近活动</p>
                </div>
            `;
            return;
        }

        activityList.innerHTML = activities.map(activity => `
            <div class="activity-item">
                <div class="activity-icon ${activity.type}">
                    <i class="fas fa-${this.getActivityIcon(activity.status)}"></i>
                </div>
                <div class="activity-content">
                    <div class="activity-title">${activity.title}</div>
                    <div class="activity-time">${activity.time}</div>
                </div>
            </div>
        `).join('');
    }

    /**
     * 获取活动图标
     */
    getActivityIcon(status) {
        switch (status) {
            case 'completed': return 'check';
            case 'failed': return 'times';
            case 'processing': return 'spinner fa-spin';
            default: return 'info';
        }
    }

    /**
     * 初始化图表
     */
    initChart() {
        const canvas = document.getElementById('conversionChart');
        if (!canvas) return;

        const ctx = canvas.getContext('2d');
        
        // 简单的Canvas图表，如果需要更复杂的图表可以使用Chart.js
        this.chart = {
            canvas: canvas,
            ctx: ctx,
            data: [],
            draw: function() {
                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                
                if (this.data.length === 0) {
                    // 显示无数据提示
                    this.ctx.fillStyle = '#6c757d';
                    this.ctx.font = '16px Arial';
                    this.ctx.textAlign = 'center';
                    this.ctx.fillText('暂无数据', this.canvas.width / 2, this.canvas.height / 2);
                    return;
                }

                const padding = 40;
                const chartWidth = this.canvas.width - padding * 2;
                const chartHeight = this.canvas.height - padding * 2;
                
                const maxValue = Math.max(...this.data.map(d => Math.max(d.conversions, d.successful, d.failed)));
                const stepX = chartWidth / (this.data.length - 1);

                // 绘制网格线
                this.ctx.strokeStyle = '#e9ecef';
                this.ctx.lineWidth = 1;
                
                // 水平网格线
                for (let i = 0; i <= 5; i++) {
                    const y = padding + (chartHeight / 5) * i;
                    this.ctx.beginPath();
                    this.ctx.moveTo(padding, y);
                    this.ctx.lineTo(padding + chartWidth, y);
                    this.ctx.stroke();
                }

                // 绘制转换总数线
                this.drawLine(this.data.map(d => d.conversions), maxValue, '#007bff', '总转换数');
                
                // 绘制成功数线
                this.drawLine(this.data.map(d => d.successful), maxValue, '#28a745', '成功转换');
                
                // 绘制失败数线
                this.drawLine(this.data.map(d => d.failed), maxValue, '#dc3545', '失败转换');

                // 绘制X轴标签
                this.ctx.fillStyle = '#6c757d';
                this.ctx.font = '12px Arial';
                this.ctx.textAlign = 'center';
                this.data.forEach((item, index) => {
                    const x = padding + stepX * index;
                    this.ctx.fillText(item.date, x, this.canvas.height - 10);
                });
            },
            
            drawLine: function(values, maxValue, color, label) {
                const padding = 40;
                const chartWidth = this.canvas.width - padding * 2;
                const chartHeight = this.canvas.height - padding * 2;
                const stepX = chartWidth / (values.length - 1);

                this.ctx.strokeStyle = color;
                this.ctx.lineWidth = 2;
                this.ctx.beginPath();

                values.forEach((value, index) => {
                    const x = padding + stepX * index;
                    const y = padding + chartHeight - (value / maxValue) * chartHeight;
                    
                    if (index === 0) {
                        this.ctx.moveTo(x, y);
                    } else {
                        this.ctx.lineTo(x, y);
                    }

                    // 绘制数据点
                    this.ctx.fillStyle = color;
                    this.ctx.beginPath();
                    this.ctx.arc(x, y, 3, 0, 2 * Math.PI);
                    this.ctx.fill();
                });

                this.ctx.stroke();
            }
        };
    }

    /**
     * 更新图表数据
     */
    updateChart(trendData) {
        if (!this.chart) return;
        
        this.chart.data = trendData;
        this.chart.draw();
    }

    /**
     * 设置自动刷新
     */
    setupAutoRefresh() {
        // 每30秒刷新一次数据
        this.refreshInterval = setInterval(() => {
            this.loadDashboardData();
        }, 30000);
    }

    /**
     * 停止自动刷新
     */
    stopAutoRefresh() {
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
            this.refreshInterval = null;
        }
    }

    /**
     * 手动刷新数据
     */
    refreshData() {
        this.loadDashboardData();
    }

    /**
     * 显示错误信息
     */
    showError(message) {
        const alertDiv = document.createElement('div');
        alertDiv.className = 'alert alert-danger alert-dismissible fade show position-fixed';
        alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(alertDiv);
        
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.parentNode.removeChild(alertDiv);
            }
        }, 5000);
    }

    /**
     * 销毁实例
     */
    destroy() {
        this.stopAutoRefresh();
    }
}

// 全局实例
let dashboardManager;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    dashboardManager = new DashboardManager();
});

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
    if (dashboardManager) {
        dashboardManager.destroy();
    }
});